from flask import abort
from flask_restful import Resource, reqparse, fields, marshal
from werkzeug.security import generate_password_hash

from app.core import util
from app.models import User, db

parser = reqparse.RequestParser()
parser.add_argument('username', required=True, type=str)
parser.add_argument('password', required=True, type=str)
parser.add_argument('email', required=False)
parser.add_argument('login_time', required=False)
parser.add_argument('avatar', required=False)

resource_full_fields = {
    'id': fields.Integer,
    'email': fields.String,
    'username': fields.String,
    'password': fields.String,
    'avatar': fields.String,
    'login_time': fields.Integer
}


class Users(Resource):
    def get(self, id):
        user = User.query.filter_by(id=id).first()

        if (user is None):
            util.make_abort(410, "找不到数据")
        else:
            return util.success_result(marshal(user, resource_full_fields), '获取用户信息成功.')

    def delete(self, id):
        deleteRecord = User.query.filter_by(id=id).delete()
        db.session.commit()
        if (deleteRecord):
            return util.success_result('删除编号为{}用户成功.'.format(id))

    def put(self, id):
        args = parser.parse_args()
        user_name = args['username']
        password = args['password']
        email = args['email']
        avatar = args['avatar']
        try:
            user = User.query.filter_by(id=id).first()
            user.username = user_name
            user.password = generate_password_hash(password)
            user.email = email
            user.avatar = avatar
            db.session.commit()
            return util.success_result(marshal(user, resource_full_fields))
        except:
            db.session.rollback()
            db.session.flush()
            abort(409, msg="修改失败", data=None, status=0)


class UserList(Resource):
    def get(self):
        return util.success_result(marshal(User.query.all(), resource_full_fields))

    def post(self):
        args = parser.parse_args()
        user_name = args['username']
        password = args['password']
        email = args['email']
        avatar = args['avatar']
        # 判断用户是否已经存在
        user = User.query.filter_by(username=user_name).first()
        if (user):
            return util.error_result('用户已经存在')
        try:
            user = User()
            user.username = user_name
            user.password = generate_password_hash(password)
            user.email = email
            user.avatar = avatar
            db.session.add(user)
            db.session.commit()
            return util.success_result(marshal(user, resource_full_fields))
        except:
            db.session.rollback()
            db.session.flush()
            util.make_abort(500, "添加失败")


# 用户注册
class UserRegister(Resource):
    def post(self):
        args = parser.parse_args()
        user_name = args['username']
        password = args['password']
        email = args['email']
        avatar = args['avatar']

        # 判断用户是否已经存在
        user = User.query.filter_by(username=user_name).first()
        if (user):
            return util.error_result('用户已经存在')
        try:
            user = User()
            user.username = user_name
            user.password = generate_password_hash(password)
            user.email = email
            user.avatar = avatar
            db.session.add(user)
            db.session.commit()
            return util.success_result(marshal(user, resource_full_fields), '注册成功')
        except:
            db.session.rollback()
            db.session.flush()
            return util.error_result('注册失败')
